package com.cloudcc.mobile.weight;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class PSImageProgress extends ImageView {

	private Paint mRemainedPaint;

	private Paint mLoadPaint;

	private Paint mTextPaint;

	private float mProgress;

	public PSImageProgress(Context context) {

		this(context, null);
	}

	public PSImageProgress(Context context, AttributeSet attrs) {
		super(context, attrs);
		this.init();
	}

	private void init() {
		mProgress = 1;

		mRemainedPaint = new Paint();
		mRemainedPaint.setColor(Color.BLACK);
		mRemainedPaint.setAlpha(150);

		mLoadPaint = new Paint();
		mLoadPaint.setColor(Color.BLACK);
		mLoadPaint.setAlpha(0);

		mTextPaint = new Paint();
		mTextPaint.setColor(Color.WHITE);
		mTextPaint.setTextSize(sp2px(this.getContext(), 12));

	}

	@Override
	public void setLayoutParams(LayoutParams params) {
		super.setLayoutParams(params);
	}

	public void setProgress(float progress) {
		if (progress > 1) {
			mProgress = 1;
		} else {
			mProgress = progress;
		}
		this.invalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {

		super.onDraw(canvas);

		Rect remainedRect = new Rect(0, 0, getWidth(),
				(int) (getHeight() * (1 - mProgress)));
		canvas.drawRect(remainedRect, mRemainedPaint);

		Rect loadRect = new Rect(0, (int) (getHeight() * (1 - mProgress)),
				getWidth(), getHeight());
		canvas.drawRect(loadRect, mLoadPaint);

		// 绘制文字
		if ((int) (mProgress * 100) != 100) {
			String percentText = (int) (mProgress * 100) + "%";
			float tW = mTextPaint.measureText(percentText);
			float tH = sp2px(this.getContext(), 12);

			canvas.drawText(percentText, (int) ((getWidth() - tW) / 2),
					(int) ((getHeight() - tH) / 2), mTextPaint);

		}
	}

	private int sp2px(Context context, float spValue) {
		final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
		return (int) (spValue * fontScale + 0.5f);
	}
}
